package org.jeecgframework.web.system.service.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.web.system.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mengtian_tech.smart_lab.entity.system.TSRole;
import com.mengtian_tech.smart_lab.entity.system.TSRoleUser;
import com.mengtian_tech.smart_lab.entity.system.TSUser;
 
@Service("userService")
@Transactional
public class UserServiceImpl extends CommonServiceImpl implements UserService {

	public TSUser checkUserExits(TSUser user){
		return this.commonDao.getUserByUserIdAndUserNameExits(user);
	}
	public String getUserRole(TSUser user){
		return this.commonDao.getUserRole(user);
	}
	
	public void pwdInit(TSUser user,String newPwd) {
			this.commonDao.pwdInit(user,newPwd);
	}
	
	public int getUsersOfThisRole(String id) {
		Criteria criteria = getSession().createCriteria(TSRoleUser.class);
		criteria.add(Restrictions.eq("TSRole.id", id));
		int allCounts = ((Long) criteria.setProjection(
				Projections.rowCount()).uniqueResult()).intValue();
		return allCounts;
	}
	@Override
	public boolean isAdmin(TSUser user) {
		 
		List<TSRoleUser> sRoleUser = findByProperty(TSRoleUser.class, "TSUser.id", user.getId());
		for (TSRoleUser tsRoleUser : sRoleUser) {
			if(TSRole.ROLE_ADMIN_ID.equals(tsRoleUser.getTSRole().getId())){
				return true;
			}
		}
		return false;
		 
	}
	
	@Override
	public TSUser findUserByStaffNoAndUserType(String staffNo, Integer userType) {
		List<TSUser> list =  findByQueryString(
				"from TSUser a where a.staffNo = ? and a.userType=?",
				new Object[]{staffNo, userType});
		if(list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
	}
	@Override
	public TSUser findByStaffNo(String staffNo) {
		

		List<TSUser> list =  findByQueryString(
				"from TSUser a where a.staffNo = ?",
				new Object[]{staffNo});
		if(list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
		
	}
	@Override
	public TSUser findTeacherByName(String teacherName) {
		List<TSUser> list =  findByQueryString(
				"from TSUser a where a.realName = ? and a.userType=?",
				new Object[]{teacherName,2});
		if(list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
	}
}
